package com.zt.algorithm.search;

/**
 * @ClassName: BinarySearch
 * @Description: BinarySearch
 * @Author: tao.zhang1
 * @Date: 2019/12/5 14:18
 * @Version: V1.0
 **/

/**
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 *
 * 你可以假设数组中无重复元素。
 */
public class BinarySearch {
    public static void main(String[] args) {
        int a[] = {1,2,4,7,8,9,10};
        int target = 5;
        System.out.println(searchInsert(a,target));
    }


    public static int searchInsert(int[] nums, int target) {
        int position = -1;
        int length = nums.length;
        if(target > nums[length-1]){
            return length;
        }
        int left = 0;
        int right = length-1;
        while (left<=right){
            int mid = (left+right)/2;
            if(nums[mid] == target){
                position = mid;
                break;
            }else if(nums[mid] > target){
                right = mid-1;
            }else {
                left = mid+1;
            }
        }
        if(position ==-1){
            System.out.println(left);
            position = left;
        }
        return position;
    }
}
